#include "EVProcess.h"
#include "EVDebug.h"



EVProcess::EVProcess()
{
}


EVProcess::~EVProcess()
{
}


DWORD EVProcess::GetPidByName(const std::wstring& sName)
{
   HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
   if (hSnapshot == INVALID_HANDLE_VALUE) return 0;

   PROCESSENTRY32 sEntry;
   sEntry.dwSize = sizeof(sEntry);

   if (Process32First(hSnapshot, &sEntry))
   {
       do
       {
		   if (_tcsicmp(sEntry.szExeFile, sName.c_str()) == 0)
           {
               CloseHandle(hSnapshot);
               return sEntry.th32ProcessID;
           }
       } while (Process32Next(hSnapshot, &sEntry));
   }


   CloseHandle(hSnapshot);
   return 0;
}


HMODULE EVProcess::GetProcessModule(const std::wstring sName, const std::wstring& sDllPath)
{

	DWORD dwPid = GetPidByName(sName);
    if (dwPid == 0)
    {
        return FALSE;
    }

	return GetProcessModule(dwPid, sDllPath);
}

HMODULE EVProcess::GetProcessModule(DWORD dwPid, const std::wstring sDllPath)
{

    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPid);
    if (hSnap == INVALID_HANDLE_VALUE) return 0;

    MODULEENTRY32 sEntry;
    sEntry.dwSize = sizeof(sEntry);

    if (Module32First(hSnap, &sEntry))
    {
        do
        {
            if (_tcsicmp(sEntry.szExePath, sDllPath.c_str()) == 0)
            {
                CloseHandle(hSnap);
                return sEntry.hModule;
            }

        } while (Module32Next(hSnap, &sEntry));
    }
    

    CloseHandle(hSnap);
    return 0;
}


HMODULE EVProcess::GetProcessModuleByName(DWORD dwPid, const std::wstring sDllName)
{
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPid);
	if (hSnap == INVALID_HANDLE_VALUE) return 0;

	MODULEENTRY32 sEntry;
	sEntry.dwSize = sizeof(sEntry);

	if (Module32First(hSnap, &sEntry))
	{
		do
		{
			if (_wcsicmp(sEntry.szModule, sDllName.c_str()) == 0)
			{
				CloseHandle(hSnap);
				return sEntry.hModule;
			}

		} while (Module32Next(hSnap, &sEntry));
	}


	CloseHandle(hSnap);
	return 0;
}

bool EVProcess::TerminateProcessId(UINT dwPid)
{
	HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwPid);
	if (hProcess != NULL){
		TerminateProcess(hProcess, 0);
		CloseHandle(hProcess);
		return true;
	}

	return false;
}

bool EVProcess::EnableDebugPrivilege()
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;
    tkp.PrivilegeCount = 1;
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
        return false;
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid);
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
    {
        return false;
    }

	CloseHandle(hToken);
    return true;
}